package com.cplatform.movie.back.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import net.sf.ezmorph.bean.MorphDynaBean;
import net.sf.json.JSONObject;

import org.apache.commons.net.util.Base64;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * Title.直接请求URL的工具类 <br>
 * Description.
 * <p>
 * Copyright: Copyright (c) 2013-9-24 下午05:01:43
 * <p>
 * Company: 北京宽连十方数字技术有限公司
 * <p>
 * Author: macl@c-platform.com
 * <p>
 * Version: 1.0
 * <p>
 */
public class RequestUrl {

	private static final Logger log = Logger.getLogger(RequestUrl.class);

	private static final String GET = "GET";

	private static final String POST = "POST";

	public static String get(String url) throws Exception {
		return doReq(GET, url);
	}

	public static String post(String url) throws Exception {
		return doReq(POST, url);
	}

	private static String doReq(String method, String url) throws Exception {
		log.info("请求url=" + url);
		HttpURLConnection httpConn = null;
		OutputStream out = null;
		BufferedReader br = null;
		try {
			httpConn = (HttpURLConnection) new URL(url.toString()).openConnection();
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			httpConn.setRequestMethod(method);
			httpConn.setConnectTimeout(1000 * 20); // 超时时间
			httpConn.setRequestProperty("event-transaction-id", "1000");
			httpConn.setRequestProperty("event-type-id", "1000");
			httpConn.setRequestProperty("Content-type", "text/html");
			out = httpConn.getOutputStream();
			out.flush();
			out.close();
			br = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "utf-8"));
			final StringBuffer msg = new StringBuffer(255);
			String line = "";
			while ((line = br.readLine()) != null) {
				msg.append(line);
			}
			return msg.toString();
		}
		catch (Exception e) {
			throw e;
		}
		finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
				}
				catch (IOException e) {
					throw e;
				}
			}
			if (br != null) {
				try {
					br.close();
				}
				catch (IOException e) {
					throw e;
				}
			}
			httpConn.disconnect();
		}
	}

	/**
	 * 调用商品相关接口
	 */
	public static MorphDynaBean doSycnReq(String url, String jsonStr) {
		MorphDynaBean object = null;
		HttpURLConnection con = null;
		OutputStream out = null;
		BufferedReader br = null;
		try {
			log.info("电影票商品同步发送给接口的数据: " + url + "=" + jsonStr);
			byte[] data = jsonStr.getBytes("utf-8");
			con = (HttpURLConnection) new URL(url).openConnection();
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setRequestMethod("POST");
			con.setConnectTimeout(1000 * 10);
			con.setRequestProperty("Content-Length", String.valueOf(data.length));
			con.setRequestProperty("Content-type", "application/json;charset=utf-8");

			out = con.getOutputStream();
			out.write(data);
			out.flush();
			out.close();
			br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
			final StringBuffer str = new StringBuffer(255);
			String line = "";
			while ((line = br.readLine()) != null) {
				str.append(line);
			}
			log.info("电影票商品同步接口返回的数据：" + str.toString());
			JSONObject json = JSONObject.fromObject(str.toString());
			object = (MorphDynaBean) JSONObject.toBean(json);
		}
		catch (Exception e) {
			log.error("电影票商品同步未知异常:" + e.getMessage());
		}
		finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
				}
				catch (IOException e) {
					log.error(e.getMessage());
				}
			}
			if (br != null) {
				try {
					br.close();
				}
				catch (IOException e) {
					log.error(e.getMessage());
				}
			}
		}

		return object;
	}

	/**
	 * hmacsha1算法
	 * 
	 * @param source
	 *            源字串
	 * @param key
	 *            key
	 * @return 摘要结果
	 */
	public static String hmacSha1(String source, String key) {
		try {
			SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
			Mac mac = Mac.getInstance("HmacSHA1");
			mac.init(keySpec);
			byte[] result = mac.doFinal(source.getBytes());
			return Base64.encodeBase64String(result);
		}
		catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}

	/**
	 * 获取随机 数字字母组合字符串
	 */
	public static String getCharAndNumr(int length) {
		String val = "";
		Random random = new Random();
		for (int i = 0; i < length; i++) {
			String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字
			if ("char".equalsIgnoreCase(charOrNum)) // 字符串
			{
				int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; // 取得大写字母还是小写字母
				val += (char) (choice + random.nextInt(26));
			} else if ("num".equalsIgnoreCase(charOrNum)) // 数字
			{
				val += String.valueOf(random.nextInt(10));
			}
		}

		return val;
	}

	/**
	 * 同步商品图片的接口
	 * 
	 * @param actionUrl 同步接口地址
	 * @param params
	 * @param stringParams 其他参数值
	 * @param fileParams 图片文件类
	 * @return
	 * @throws Exception
	 */
	public static JsonNode doSyncItemImgs(String actionUrl, Map<String, String> params, List<String[]> stringParams, List<String[]> fileParams)
	        throws Exception {
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		String encoding = "utf-8";
		StringBuilder newUrl = new StringBuilder();
		newUrl.append(actionUrl);

		if (params != null) {
			for (Map.Entry<String, String> item : params.entrySet()) {
				String itemParam = item.getKey() + "=" + java.net.URLEncoder.encode(item.getValue(), encoding);
				if (newUrl.indexOf("?") > -1) {
					newUrl.append("&").append(itemParam);
				} else {
					newUrl.append("?").append(itemParam);
				}
			}
		}
		log.info("电影票商品同步图片发送给接口的数据:" + newUrl.toString());
		URL url = null;
		// http连接器
		HttpURLConnection con = null;
		// byte输出流，用来读取服务器返回的信息
		DataOutputStream ds = null;
		try {
			url = new URL(newUrl.toString());
			con = (HttpURLConnection) url.openConnection();
			// 发送POST请求必须设置如下两行
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			con.setRequestMethod("POST");
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", encoding);
			con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
			ds = new DataOutputStream(con.getOutputStream());

			// 字符串参数提交
			if (stringParams != null) {
				for (String[] param : stringParams) {
					ds.writeBytes(twoHyphens + boundary + end);
					ds.writeBytes("Content-Disposition: form-data;name=\"" + param[0] + "\"");
					ds.writeBytes(end);
					ds.writeBytes(end);
					ds.write(param[1].getBytes(encoding));
					ds.writeBytes(end);
				}
			}

			// 文件提交
			if (fileParams != null) {
				for (int i = 0; i < fileParams.size(); i++) {
					String[] uploadFile = fileParams.get(i);
					String filename = uploadFile[1];
					ds.writeBytes(twoHyphens + boundary + end);
					ds.write(("Content-Disposition: form-data; " + "name=\"" + uploadFile[0] + "\";filename=\"" + filename + "\"" + end)
					        .getBytes(encoding));
					ds.writeBytes(end);
//					URL imgPath = new URL(uploadFile[3]);
//					BufferedInputStream fStream = new BufferedInputStream(imgPath.openStream()); 
					FileInputStream fStream = new FileInputStream(uploadFile[3]);
					int bufferSize = 1024;
					byte[] buffer = new byte[bufferSize];
					int length = -1;
					while ((length = fStream.read(buffer)) != -1) {
						ds.write(buffer, 0, length);
					}
					ds.writeBytes(end);
					fStream.close();
				}
			}

			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
			ds.flush();

			// 读取服务器返回信息
			final BufferedReader bufferedReader;
			if (encoding == null || encoding.length() == 0) {
				bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
			} else {
				bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream(), encoding));
			}

			String line;
			final StringBuilder stringBuffer = new StringBuilder(255);

			while ((line = bufferedReader.readLine()) != null) {
				stringBuffer.append(line);
				stringBuffer.append("\n");
			}

			log.info("电影票商品同步图片接口返回的数据:" + stringBuffer.toString());
			ObjectMapper mapper = new ObjectMapper();
			return mapper.readTree(stringBuffer.toString());
		}
		catch (Exception e) {
			throw e;
		}
		finally {
			if (ds != null) {
				try {
					ds.close();
				}
				catch (IOException e) {
					log.error(e.getMessage());
				}
			}
			if (con != null) {
				con.disconnect();
			}
		}
	}

}
